require('./index.scss');
var template = require('./template.html');

var comp = avalon.component('ms-dialog', {
    template: template,
    defaults: {
        dialog:{
            display:"none",
            title: '',
            hideClose:false,
            className:'',
            desc:'',
            close(){},
            solve(){}
        },
        onReady:function(e){
            var that = this,
                dialogHeight,
                loop;
            if(that.dialog.display=='block') setDialog();
            e.vmodel.$watch('dialog.display', function(newval){
                if(newval=='none') {
                    $("body").removeClass('hidden');
                    $("#dialogMask").remove();
                    clearInterval(loop);
                }else{
                    setDialog();
                }
            });
            function setDialog(){
                if( $("#dialogMask").length===0 )
                    $("body").addClass('hidden').prepend('<div id="dialogMask" class="dialogMask"></div>');
                
                var dialogCon = $(e.target).find('.dialogCon');
                var $h2_title = $(e.target).find('.h2');
                if($h2_title.length>0) startDrag( $h2_title[0], dialogCon[0]);        // 拖动效果
                setPosition();
                loopHeight();
            }
            // 定时监控弹窗的高度，设置弹窗上下居中
            function loopHeight(){
                clearInterval(loop);
                var dialogCon = $(e.target).find('.dialogCon');
                dialogHeight = dialogCon.outerHeight();
                loop = setInterval(function(){
                    var _height = dialogCon.outerHeight();
                    if( _height!=dialogHeight ) setPosition();
                }, 200);
            }

            // 设置弹窗上下居中
            function setPosition(){
                var dialogCon = $(e.target).find('.dialogCon'),
                    winWidth = $(window).width(),
                    winHeight = $(window).height(),
                    _left = winWidth/2 - dialogCon.width()/2,
                    _top = winHeight/2 - dialogCon.height()/2;
                if( _top<10 ) _top=10;
                dialogCon.css({'left':_left,'top':_top});
            }
        }
    },
    soleSlot: 'slot'
});

module.exports = comp;